<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- 用form包裹起来用于实现输入键盘上面有搜索功能按钮 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false"
        background="#3296fa"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
  <search-result v-if="isResultShow" :search-text="searchText"></search-result>
  <!-- /搜索结果 -->

  <!--联想建议  -->
  <search-suggestion @search="onSearch" :search-text="searchText" v-else-if="searchText"></search-suggestion>
  <!--/联想建议  -->

  <!-- 搜索历史记录 -->
  <search-history @search="onSearch" v-else @clear-search-histories="searchHistories=[]" :search-histories="searchHistories"></search-history>
  <!-- /搜索历史记录 -->
  </div>
</template>
<script>
import SearchHistory from "./components/search-history"
import SearchSuggestion from "./components/search-suggestion"
import SearchResult from "./components/search-result"
import { setItem,getItem} from "@/utils/storage"
export default {
  data() {
    return {
      searchText: "",
      isResultShow:false,  //控制搜索结果展示
      searchHistories:getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 搜索的历史记录
    };
  },
  watch:{
    searchHistories(val){
      setItem('TOUTIAO_SEARCH_HISTORIES',val)
    }
  },
  methods: {
    onSearch(val) {
      // 更新文本框内容
      this.searchText = val;
      // 存储搜索历史记录
      // 要求：不要有重复历史记录，最新的排在最前面
      const index = this.searchHistories.indexOf(val)
      if(index!==-1){
        this.searchHistories.splice(index,1)
      }
      this.searchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true;
      
    },
    onCancel() {
      this.$router.back();
    },
  },
  components: {
      SearchHistory,SearchSuggestion,SearchResult
  },
};
</script>
<style scoped lang="less">
.search-container {
  padding-top: 108px;
  height: 100vh;
  box-sizing: border-box;
  overflow-y: scroll;
  .van-search__action {
    color: #fff;
  }
  .search-form{
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 1;
  }
}
</style>